#include "FieldModel.h"

FieldModel::FieldModel(Format *format, FERange range, void *context, QObject *parent)
    : QAbstractItemModel{parent}
{
    FEFieldNode node;
    node.field = format->getTopField();
    node.range = range;
    node.context = context;
    node.free = nullptr;
    node.index1 = -1;
    node.index2 = -1;
    node.index3 = -1;
    node.translate_type = FEFieldNode::Raw;
    root_item_ = new FieldItem(nullptr, &node, nullptr);
    auto top_item = new FieldItem(format, &node, root_item_);
    root_item_->appendChild(top_item);
}

FieldModel::~FieldModel()
{
    if (root_item_) {
        delete root_item_;
        root_item_ = nullptr;
    }
}

QModelIndex FieldModel::index(int row, int column, const QModelIndex& parent) const {
    if (!hasIndex(row, column, parent))
        return QModelIndex();

    FieldItem* parentItem = getItem(parent);
    FieldItem* childItem = parentItem->child(row);
    if (childItem)
        return createIndex(row, column, childItem);
    return QModelIndex();
}

QModelIndex FieldModel::parent(const QModelIndex& index) const  {
    if (!index.isValid())
        return QModelIndex();

    FieldItem* childItem = getItem(index);
    FieldItem* parentItem = childItem->parent();

    if (parentItem == root_item_)
        return QModelIndex();

    return createIndex(parentItem->row(), 0, parentItem);
}

int FieldModel::rowCount(const QModelIndex& parent) const  {
    FieldItem* parentItem = getItem(parent);
    return parentItem->childCount();
}

int FieldModel::columnCount(const QModelIndex& parent) const  {
    Q_UNUSED(parent);
    return 1; // 只有一列数据
}

QVariant FieldModel::data(const QModelIndex& index, int role) const  {
    //    if (!index.isValid())
    //        return QVariant();

    FieldItem* item = getItem(index);
    if (role == Qt::DisplayRole) {
        //        qDebug() << "data" << item->data(index.column());
        return item->data(index.column());
    }

    return QVariant();
}

void FieldModel::selectItem(const QModelIndex &index)
{
    auto item = getItem(index);
    if(item)
        emit rangeChanged(item->range());
}

FieldItem* FieldModel::getItem(const QModelIndex& index) const {
    if (index.isValid()) {
        FieldItem* item = static_cast<FieldItem*>(index.internalPointer());
        if (item)
            return item;
    }
    return root_item_;
}
